var util = require('./util.js');
var app = getApp();
var innerAudioContext;

var wxUtil = {
    // 调用微信支付接口
    wxPay: function(param) {
        var _this = this;
        wx.requestPayment({
            'timeStamp': param.timeStamp,
            'nonceStr': param.nonceStr,
            'package': param.package,
            'signType': 'MD5',
            'paySign': param.paySign,
            success: function(res) {
                typeof param.success === 'function' && param.success();
                _this.wxPaySuccess(param);
            },
            fail: function(res) {
                if (res.errMsg === 'requestPayment:fail cancel' || 'requestPayment:fail') {
                    return;
                }
                util.alert(res.errMsg)
                _this.wxPayFail(param, res.errMsg);
            }
        })
    },
    wxPaySuccess: function(param) {},
    wxPayFail: function(param, errMsg) {},

    /**
     * 上传文件
     * @param  {[type]} localImgUrl [description]
     * @return {[type]}             [description]
     */
    upload: (localImgUrl, cb, failCb) => {
        wx.uploadFile({
            url: app.config.apiUrl + '/api/common/upload?sid=' + app.globalData.sid,
            filePath: localImgUrl,
            name: 'file',
            header: {
                'content-type': 'multipart/form-data',
            },
            success: (res) => {
                try {
                    res = JSON.parse(res.data);
                } catch (e) {}

                if (res.code == 0) {
                    var imgUrl = res.result.url;
                    cb && cb(imgUrl, res);
                } else {
                    failCb && failCb(res);
                }
            }
        })
    },

    playVoice({
        url
    }) {
        if (!url) {
            return;
        }
        if (!innerAudioContext) {
            innerAudioContext = wx.createInnerAudioContext()
            innerAudioContext.onPlay(() => {})
            innerAudioContext.onError((res) => {})
            innerAudioContext.onEnded((res) => {})
            innerAudioContext.onStop((res) => {})
        } else {
            innerAudioContext.stop()
        }
        innerAudioContext.src = url;
        innerAudioContext.play();
    },

};

module.exports = wxUtil;